import Vue from 'vue'
import VueRouter from 'vue-router'
import VueCookies from "vue-cookies";
import Login from "@/components/Login";
import Main from "@/components/Main";
import Home from "@/components/Home";
import Student from "@/components/Student";
import Exam from "@/components/exam/Exam";
import Teachers from "@/components/Teachers";
import ClassTable from "@/components/ClassTable";
import ExamList from "@/components/exam/ExamList";
import Path_404 from '@/components/404'
import ExamDetail from "@/components/exam/ExamDetail";
import EnterExam from "@/components/exam/EnterExam";

// 重复点击导航时，控制台报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

const child = [
    {name: 'home', path: 'home', component: Home, meta: {title: "我的首页"}},
    {name: 'student', path: 'student', component: Student, meta: {title: "学生管理"}},
    {
        name: 'exam', path: 'exam', component: Exam, redirect: 'exam/examlist', meta: {title: "考试列表"}, children: [
            {name: 'examList', path: 'examlist', component: ExamList, meta: {title: "我的考试列表"}},
            {name: 'examDetail', path: 'examdetail', component: ExamDetail, meta: {title: "试卷详情"}},
            {name: 'enterExam', path: 'enterexam', component: EnterExam, meta: {title: "正在考试"}},
        ]
    },
    {name: 'teacher', path: 'teacher', component: Teachers, meta: {title: "我的老师"}},
    {name: 'classtable', path: 'classtable', component: ClassTable, meta: {title: "我的课表"}},
    {name: 404, path: '/404', component: Path_404, meta: {title: "您当前访问的页面不存在"}}
]

Vue.use(VueRouter)

const routes = [
    {name: 'login', path: '/login', component: Login, meta: {title: "登录"}},
    {name: 'main', path: "/", component: Main, redirect: 'home', children: child}
]

const router = new VueRouter({
    routes
})

router.beforeEach((to, from, next) => {

    if (to.meta.title) {
        document.title = to.meta.title
    }

    if (to.matched.length === 0) {
        next('/404') // 判断此跳转路由的来源路由是否存在，存在的情况跳转到来源路由，否则跳转到404页面
    }

    const token = VueCookies.get('token')
    if (!token && to.name !== 'login') {
        next({name: 'login'})
    } else if (token && to.name === 'login') {
        next({name: 'home'})
    } else {
        next()
    }
})

export default router
